﻿using System.Collections.Concurrent;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;

namespace Dx.DDD.Repositories
{
    /// <summary>
    /// 工作单元使用相关扩展
    /// </summary>
    public static class UnitOfWorkExt
    {
        private static readonly ConcurrentDictionary<string, HashSet<string>> dic = new();
        /// <summary>
        /// 判断action是否带有工作单元
        /// </summary>
        /// <param name="fullName"></param>
        /// <returns></returns>
        public static bool IsUnitOfWork(this string fullName, [MaybeNullWhen(false)] out HashSet<string> unitOfWork)
        {
            var isUnitOfWork = dic.TryGetValue(fullName, out unitOfWork);
            if (!isUnitOfWork) return isUnitOfWork;
            if (unitOfWork?.Count == 0) return false;
            return isUnitOfWork;
        }
        /// <summary>
        /// 中间件中获取控制器的方法全名包括命名空间
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static string SubstringBeforeSpace(this string input)
        {
            int spaceIndex = input.IndexOf(' ');
            return spaceIndex >= 0 ? input[..spaceIndex] : input;
        }
        /// <summary>
        /// 带有工作单元的控制器添加到字典
        /// </summary>
        /// <param name="unitOfWork"></param>
        /// <param name="fullName">控制器名称，命名空间.类名.方法名</param>
        public static void Add(this UnitOfWorkAttribute unitOfWork, string fullName)
        {
            var hset = dic.GetOrAdd(fullName, x => new HashSet<string>());
            if (!string.IsNullOrWhiteSpace(unitOfWork.ConnectionString)) 
            {
                hset.Add(unitOfWork.ConnectionString);
            }
        }
    }
}
